package com.hcb.webservice;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class ImageUtils {
	private static ImageUtils instance;

	public static ImageUtils getInstance() {
		if (instance == null)
			instance = new ImageUtils();
		return instance;
	}

	public int uploadFile(String sourceFileUri, String urlPath) {
		int serverResponseCode = -1;
		String upLoadServerUri = urlPath;
		String fileName = "&#63"+sourceFileUri;
		//&#63
		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		File sourceFile = new File(sourceFileUri);
		if (!sourceFile.isFile()) {
			Log.e("uploadFile", "Source File Does not exist");
			return 0;
		}
		try { // open a URL <span class="IL_AD" id="IL_AD12">connection</span>
				// to the Servlet
			FileInputStream fileInputStream = new FileInputStream(sourceFile);
			URL url = new URL(upLoadServerUri);
			conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
																// connection to
																// the URL
			conn.setDoInput(true); // Allow Inputs
			conn.setDoOutput(true); // Allow Outputs
			conn.setUseCaches(false); // Don't use a Cached Copy
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("ENCTYPE", "multipart/form-data");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			// //////////// TEST
			conn.setRequestProperty("image", "abc");

			conn.setRequestProperty("file_contents", fileName);
			dos = new DataOutputStream(conn.getOutputStream());

			dos.writeBytes(twoHyphens + boundary + lineEnd);
			dos.writeBytes("Content-Disposition: form-data; name=\"file_contents\";filename=\""
					+ fileName + "\"" + lineEnd);
			dos.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available(); // create a buffer of
															// maximum size

			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// read file and write it into form...
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// send multipart form data necesssary after file data...
			dos.writeBytes(lineEnd);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// Responses from the server (code and message)
			serverResponseCode = conn.getResponseCode();
			String serverResponseMessage = conn.getResponseMessage();

			Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
					+ ": " + serverResponseCode);

			// close the streams //
			fileInputStream.close();
			dos.flush();
			dos.close();

		} catch (MalformedURLException ex) {
			Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
		} catch (Exception e) {
			Log.e("Upload file to server Exception",
					"Exception : " + e.getMessage(), e);
		}

		return serverResponseCode;
	}
	public Bitmap getBimapFromSdcard(String pathName) {
		String path = Environment.getExternalStorageDirectory()
				+ File.separator + pathName;
		File imgFile = new File(path);
		if (imgFile.exists()) {
			Bitmap myBitmap = BitmapFactory.decodeFile(imgFile
					.getAbsolutePath());
			
			return myBitmap;
		}
		
		return null;
	}

	//
	// /**
	// * Decode string to image
	// * @param imageString The string to decode
	// * @return decoded image
	// */
	// public static BufferedImage decodeToImage(String imageString) {
	//
	// BufferedImage image = null;
	// byte[] imageByte;
	// try {
	// BASE64Decoder decoder = new BASE64Decoder();
	// imageByte = decoder.decodeBuffer(imageString);
	// ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
	// image = ImageIO.read(bis);
	// bis.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return image;
	// }
	//
	// private String getStringFromBitmap(Bitmap bitmapPicture) {
	// final int COMPRESSION_QUALITY = 100;
	// String encodedImage;
	// ByteArrayOutputStream byteArrayBitmapStream = new
	// ByteArrayOutputStream();
	// bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
	// byteArrayBitmapStream);
	// byte[] b = byteArrayBitmapStream.toByteArray();
	// encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
	// return encodedImage;
	// }
	//
	// private Bitmap getBitmapFromString(String jsonString) {
	// /*
	// * This Function converts the String back to Bitmap
	// * */
	// byte[] decodedString = Base64.decode(jsonString, Base64.DEFAULT);
	// Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
	// decodedString.length);
	// return decodedByte;
	// }
	//
	// /**
	// * Encode image to string
	// * @param image The image to encode
	// * @param type jpeg, bmp, ...
	// * @return encoded string
	// */
	// public static String encodeToString(BufferedImage image, String type) {
	// String imageString = null;
	// ByteArrayOutputStream bos = new ByteArrayOutputStream();
	//
	// try {
	// ImageIO.write(image, type, bos);
	// byte[] imageBytes = bos.toByteArray();
	//
	// BASE64Encoder encoder = new BASE64Encoder();
	// imageString = encoder.encode(imageBytes);
	//
	// bos.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return imageString;
	// }

}
